
    //视图组件，我们要把它转换成容器组件
import React,{Component} from 'react';
import {connect} from 'react-redux';
import {increase,decrease,fetchList,addToCart} from '../actions/counter';//counter.js中暴露的方法

    class Counter extends Component{
        componentWillMount(){//钩子函数
            this.props.fetchList();
        }
    
        changePage(e){//页码按钮
           const page = e.target.getAttribute('data-page');//获取当前的页码
           const params = {page:parseInt(page)};
        //    console.log(params)
           this.props.fetchList(params)
        }

        addCart(e){//加入购物出按钮
            const idx = e.target.getAttribute('data-idx');//获取商品的下标
            const addToCartProduct = this.props.lists.subjects[idx];//获取选中的整个对象
            this.props.addToCart(addToCartProduct)
        }

        render(){
            const {value,value1,lists,carts,increase,decrease,fetchList,addToCart} = this.props;//counter.js中所有暴露的方法
            var output = [];
            if(!lists.subjects){
                return <div>数据请求中。。。</div>
            }
            var output = [];
            var outputPages = [];
            var pages =  1;
                pages = Math.ceil(lists.total/20)//pages为总共的页数
            for(let i=1;i<=pages;i++){//创建分页
                outputPages.push(
                    <li><a href="javascript:void(0)" onClick={(e)=>this.changePage(e)} data-page={i} key={i}>{i}</a></li>//data-page为传值
                )
            }
            for(let i=0;i<lists.subjects.length;i++){//遍历获取数据
                output.push(<li key={i}>
                    {lists.subjects[i].title}
                    <a className="btn btn-primary" role="button" href="javascript:void(0)" data-idx={i}  onClick={ (e)=> {this.addCart(e)} }>加入购物车</a>
                    </li>)
            }
            return(
                <div> 
                    <span>value：{value}</span><br/>
                    <span>value1：{value1}</span><br/>
                    <nav aria-label="...">
                        <ul className="pagination">
                            {outputPages}
                        </ul>
                    </nav>
                    <br/>
                    {output}
                    <button onClick={increase}>计数+1</button>
                    <button onClick={decrease}>计数-1</button>
                    
                    
                    
                </div>
            )
        }
    }

    const getValue = (state)=>{ 
        // console.log(state)
        return{
            value:state.reducer.count,
            value1:state.reducer.count1,
            lists:state.reducer.lists,
        }
    }

    const CouterContext = connect(getValue,{increase,decrease,fetchList,addToCart})(Counter)//counter.js中所有暴露的方法
    
    module.exports = CouterContext;
